package edu.java.homework.hw11.enums.solution.dish;

public class Dish {

	// --- Instance Variables --------------------------------------------------
	private String name = null;
	private DishState dishState = DishState.IS_EMPTY;

	// --- Constructors --------------------------------------------------------
	public Dish(String name) {
		this.name = name;
		this.dishState = DishState.IS_EMPTY;
	}

	// --- Getters and Setters -------------------------------------------------
	public DishState getDishState() {
		return dishState;
	}

	public void setDishState(DishState dishState) {
		this.dishState = dishState;
	}

	public String getName() {
		return name;
	}

	// --- Methods -------------------------------------------------------------

	public synchronized void prepareDish() {
		while (getDishState() != DishState.IS_EMPTY) {
			try {
				System.out.println(Thread.currentThread().getName()
						+ " goes to wait because " + this.getName()
						+ " is not empty.");
				wait();// the cook waits because dish is not empty
			} catch (InterruptedException e) {
				System.out.println("Interrupted Exception in thread: "
						+ Thread.currentThread().getName());
				e.printStackTrace();
			}
		}

		// dish is empty
		if (getDishState() == DishState.IS_EMPTY) {
			System.out.println(Thread.currentThread().getName()
					+ " put the dish.");
			this.setDishState(DishState.IS_PREPARED);
			notifyAll();
		}
	}

	public synchronized void serveDish() {
		while (getDishState() != DishState.IS_PREPARED) {
			System.out.println(Thread.currentThread().getName()
					+ " goes to wait because the " + getName()
					+ " is not prepared by the cook.");

			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("Interrupted Exception in thread: "
						+ Thread.currentThread().getName());
				e.printStackTrace();
			}
		}
		// 
		if (getDishState() == DishState.IS_PREPARED) {
			System.out.println(Thread.currentThread().getName()
					+ " serves the " + getName() + " to the client. ");
			setDishState(DishState.IS_SERVED);
			notifyAll();
		}
	}

	public synchronized void eatDish() {
		while (getDishState() != DishState.IS_SERVED) {
			System.out.println(Thread.currentThread().getName()
					+ " goes to wait because the " + getName()
					+ " is not served by the waiter.");

			try {
				wait();
			} catch (InterruptedException e) {
				System.out.println("Interrupted Exception in thread: "
						+ Thread.currentThread().getName());
				e.printStackTrace();
			}
		}

		if (getDishState() == DishState.IS_SERVED) {
			System.out.println(Thread.currentThread().getName() + " eats the "
					+ getName() + " and sets free the plate. ");
			setDishState(DishState.IS_EMPTY);
			notifyAll();
		}

	}
}
